﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace AuthenticationService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    public class Service1 : IAuthenticationService
    {
        /// <summary>
        /// Authenticate a username password combination against the database of users
        /// </summary>
        /// <param name="username">Encrypted username</param>
        /// <param name="password">Encrypted password</param>
        /// <returns>Authentication response containing success/failure and the reason (in case of failure)</returns>
        public AuthenticationResponse authenticate(String username, String password)
        {
            AuthenticationResponse response = new AuthenticationResponse();

            try
            {
                EncryptionService.ServiceSoapClient encryption_client =
                    new EncryptionService.ServiceSoapClient("ServiceSoap");

                // decode the username and password
                String decrypt_username = encryption_client.Decrypt(username);
                String decrypt_password = encryption_client.Decrypt(password);

                // JSC TODO: Remove this for production (Assignment 4)
                Console.WriteLine("<<< TODO: Remove this for assignment #4\r\nReceived username: {0}[{2}] password: {1}[{3}] ", decrypt_username, decrypt_password, username, password);

                // JSC TODO: Implement server logic to check code here:
                return _authenticate(decrypt_username, decrypt_password);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            return response;
        }

        private AuthenticationResponse _authenticate(String username, String password)
        {
            AuthenticationResponse response = new AuthenticationResponse();

            if (username != "user" || password != "password")
            {
                response.Success = false;
                response.Reason = "Incorrect username or password.";
            }
            else
            { 
                response.Success = true;
                response.Reason = "Login Successful!";
            }

            return response;
        }
    }
}
